$(function () {
    var queryUrl = '../toolsdemandplan/list';
    var Id = getQueryString('Id');
    if (Id) {
        queryUrl += '?Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '计划编码', name: 'planCode', index: 'PLAN_CODE', width: 80},
            {label: '所属车间', name: 'workshopName', width: 80},
            {label: '编制单位/申请单位', name: 'deptName', index: 'APPLY_UNIT', width: 80},
            {label: '编制人', name: 'organName', index: 'ORGAN_USER', width: 80},
            {label: '编制月份', name: 'organMonth', index: 'ORGAN_MONTH', width: 80},
            {
                label: '当前进度', name: 'progress', index: 'PROGRESS', width: 80,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_NEEDS_PLAN_PROGRESS[row.progress];
                }
            },
            {
                label: '是否已导出', name: 'isExported', index: 'IS_EXPORTED', width: 60,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_NEEDS_PLAN_EXPORT_STATUS[row.isExported];
                }
            },
            {name: 'progress', hidden: true},
            {
                label: '审核详情', name: 'devCode', index: 'DEV_CODE', width: 80,sortable:false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;详情</button>";
                }
            },
            {label: '', name: 'deptApprovalName', index: 'DEPT_APPROVAL_USER', hidden: true},
            {
                label: '', name: 'deptApprovalStatus', index: 'DEPT_APPROVAL_STATUS', hidden: true,
                formatter: function (value) {
                    return sysEnums.CHECK_FLAG[value];
                }
            },
            {
                label: '', name: 'deptApprovalDate', index: 'DEPT_APPROVAL_DATE', hidden: true,
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd hh:mm");
                }
            },
            {label: '', name: 'peApprovalName', index: 'PE_APPROVAL', hidden: true},
            {
                label: '', name: 'peApprovalStatus', index: 'PE_APPROVAL_STATUS', hidden: true,
                formatter: function (value) {
                    return sysEnums.CHECK_FLAG[value];
                }
            },
            {
                label: '', name: 'peApprovalDate', index: 'PE_APPROVAL_DATE', hidden: true,
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd hh:mm");
                }
            },
            {label: '', name: 'pe2ApprovalName', index: 'PE2_APPROVAL', hidden: true},
            {
                label: '', name: 'pe2ApprovalStatus', index: 'PE2_APPROVAL_STATUS', hidden: true,
                formatter: function (value) {
                    return sysEnums.CHECK_FLAG[value];
                }
            },
            {
                label: '', name: 'pe2ApprovalDate', index: 'PE2_APPROVAL_DATE', hidden: true,
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd hh:mm");
                }
            },
            {
                label: '需求明细', width: 80, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='详细信息' class='btn btn-outline btn-info' onclick='vm.goPartDetail(\"" + row.planCode + "\", \"" + row.applyUnit + "\", \"" + row.id + "\")'><i class='fa fa-bars'></i></button>";
                    // return "<button class='btn btn-outline btn-info' onclick='vm.goPartDetail(\"" + row.planCode + "\", \"" + row.applyUnit + "\")'><i class='fa fa-bars'></i>&nbsp;详细信息</button>";
                }
            },
            /*{label: '审批状态', name: 'approvalStatus', index: 'APPROVAL_STATUS', width: 80},*/
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: 'id', name: 'applyUnit', index: 'APPLY_UNIT', hidden: true},
            {
                label: 'id', name: 'deptStatus', index: 'DEPT_APPROVAL_STATUS', hidden: true,
                formatter: function (value, col, row) {
                    return row.deptApprovalStatus;
                }
            },
            {
                label: 'id', name: 'peStatus', index: 'APPLY_UNIT', hidden: true,
                formatter: function (value, col, row) {
                    return row.peApprovalStatus;
                }
            },
            {
                label: 'id', name: 'pe2Status', index: 'APPLY_UNIT', hidden: true,
                formatter: function (value, col, row) {
                    return row.pe2ApprovalStatus;
                }
            },
            {
                label: 'id', name: 'pe3Status', index: 'APPLY_UNIT', hidden: true,
                formatter: function (value, col, row) {
                    return row.pe3ApprovalStatus;
                }
            },
            {
                label: 'id', name: 'pe4Status', index: 'APPLY_UNIT', hidden: true,
                formatter: function (value, col, row) {
                    return row.pe4ApprovalStatus;
                }
            },
            {
                label: 'id', name: 'leaderStatus', index: 'APPLY_UNIT', hidden: true,
                formatter: function (value, col, row) {
                    return row.leaderApprovalStatus;
                }
            },
        ]
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        sparePartRequ: {
            organMonth: '',
            id: ''
        },
        q: {
            planCode: '',
            organName: ''
        },
        // 审核参数VO
        approveParam:{
            approveIdList: [],
            status: 1,
            remark: ''
        },
        approveStatus: 1, // 审批状态
        approveRemark: '' // 审批备注
    },
    methods: {
        overview: function(){
            // 获取需要概览的初稿拟定计划
            var plans = getSelectedRowDatas('#jqGrid');
            if(!plans || plans.length == 0){
                iview.Message.error("请选择需求计划！");
                return;
            }
            // 创建计划编码字符串
            var planCodeArray = '';
            for (var i = 0; i < plans.length; i++) {
                planCodeArray += ',' + plans[i].planCode;
            }
            planCodeArray = planCodeArray.substring(1);
            // 备件需求计划概览
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 备件计划初稿拟定',
                content: '../tools/toolsdemandplandetail.html?isQuery=1&planCode=' + planCodeArray,
                btn: ['确定'],
                btn1: function (index) {
                    layer.close(index);
                }
            })
        },
        commit: function () {
            // 编制完毕后提交审核
            var planId = getSelectedRow("#jqGrid");
            if (!planId) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress !== '0' && data.progress !== '4') {
                alert('当前需求计划审核中或已通过，无需重复提交!');
                return;
            }
            Ajax.request({
                url: '../toolsdemandplan/commitApprove',
                params: {'spareNeedsPlanId': data.id},
                type: 'POST',
                successCallback: function (res) {
                    alert('提交成功!');
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                }
            });
        },
        deptCheck: function () {
            var data = getSelectedRowData('#jqGrid');
            if (data.progress != 1) {
                alert('只有处于[部门审核]的计划才可以执行该操作！');
                return;
            }
            this.openApproveWin('部门审核', '../toolsdemandplan/deptCheck', data.id)
        },
        peCheck: function () {
            var data = getSelectedRowData('#jqGrid');
            if (data.progress != 2) {
                alert('只有处于[PE审核]的计划才可以执行该操作！');
                return;
            }
            this.openApproveWin('PE审核', '../toolsdemandplan/peCheck', data.id)
        },
        pe2Check: function () {
            var data = getSelectedRowData('#jqGrid');
            if (data.progress != 3) {
                alert('只有处于[PE审批]的计划才可以执行该操作！');
                return;
            }
            this.openApproveWin('PE审批', '../toolsdemandplan/pe2Check', data.id)
        },
        openApproveWin: function(title, url, planId) {
            var _this = this;
            // 构建审批参数
            _this.approveParam = {
                approveIdList: [planId],
                status: '1',
                remark: ''
            }
            openWindow({
                title: title,
                area: ['500px', '260px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: url,
                        params: JSON.stringify(_this.approveParam),
                        contentType: "application/json",
                        type: 'POST',
                        successCallback: function (res) {
                            alert('审核成功!');
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                    });
                }
            });
        },
        //审核详情
        shviewOption: function (res) {
            var data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    var approveProcessList = res.approveProcessList;
                    if (approveProcessList.length == 0) {
                        iview.Message.error("暂无审批记录");
                        return;
                    }
                    var dom = "<div class='details'><table>";
                    for (var i = 0; i < approveProcessList.length; i++) {
                        var approveProcess = approveProcessList[i];
                        dom += '<tr><td>' + approveProcess.approveDate + '</td>';
                        dom += '<td align="left">' + approveProcess.roleName + '-' + approveProcess.name + '： ' + sysEnums.CHECK_FLAG[approveProcess.status];
                        if (approveProcess.remark) {
                            dom += '<br />备注：' + approveProcess.remark;
                        }
                        dom += '</td></tr>'
                    }
                    dom += '</table></div>'
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['500px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: dom
                    });
                }
            });
        },
        updateCheck: function (url, params) {
            Ajax.request({
                url: url,
                params: params,
                contentType: "application/json",
                type: 'POST',
                successCallback: function (res) {
                    alert('审核成功!');
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                }
            });
        },
        goPartDetail: function (planCode, applyUnit,planId) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 需求计划明细',
                content: '../tools/toolsdemandplandetail.html?planCode=' + planCode + '&applyUnit=' + applyUnit + '&planId=' + planId,
                cancel: function (index, layero) {
                    layer.close(index);
                    vm.reload();
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.sparePartRequ = {
                organMonth: '',
                id: ''
            };
        },
        createNeedsPlan: function(){
            if (vm.sparePartRequ.organMonth) {
                vm.sparePartRequ.organMonth = vm.GMTToStr(vm.sparePartRequ.organMonth);
            }
            /*
           校验下当前月份是否已编制过，如果已编制过需要给用户提示是否仍要继续
            */
            Ajax.request({
                url: '../toolsdemandplan/checkOrganed',
                params: {
                    organMonth: vm.sparePartRequ.organMonth
                },
                type: "POST",
                successCallback: function (r) {
                    if(r.isExists == 1){
                        confirm(vm.sparePartRequ.organMonth + '月份的车间需求计划已创建，是否仍要创建？', function () {
                            vm.saveOrUpdate();
                        });
                    }else{
                        vm.saveOrUpdate();
                    }
                }
            });
        },
        saveOrUpdate: function (event) {
            if (vm.sparePartRequ.organMonth) {
                vm.sparePartRequ.organMonth = vm.GMTToStr(vm.sparePartRequ.organMonth);
            }
            Ajax.request({
                url: "../toolsdemandplan/save",
                params: JSON.stringify(vm.sparePartRequ),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../toolsdemandplan/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: vm.q,
                page: page
            }).trigger("reloadGrid");
        },
        reloadSearch: function () {
            vm.q = {
                planCode: '',
                organName: ''
            };
            vm.reload();
        },
        GMTToStr: function (time) {
            var date = new Date(time)
            var month = date.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            return date.getFullYear() + '-' + month;
        },
        //数据导出
        exportData:function () {
            var ids = getSelectedRows('#jqGrid');
            if(!ids){
                return;
            }
            exportFile('#rrapp', '../toolsdemandplan/export', {'ids': ids});
        }
    }
});
